<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';

// --- STATE ---
const messages = ref([]);
const newMessage = ref('');
const isLoading = ref(false);
const memoryId = ref(null);
const chatContainer = ref(null);
const textareaRef = ref(null); // Ref for the textarea element
let messageIdCounter = 0;

const API_BASE_URL = 'http://localhost:8081/api';

// --- LIFECYCLE HOOKS ---
onMounted(() => {
  memoryId.value = Math.floor(Math.random() * 2147483647);
  addMessage('ai', '你好！我是你的 AI 编程助手，有什么可以帮助你的吗？');
});

// --- METHODS ---
const getUniqueMessageId = () => ++messageIdCounter;

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

const addMessage = (sender, text) => {
  messages.value.push({ id: getUniqueMessageId(), sender, text });
  scrollToBottom();
};

const autoResizeTextarea = () => {
  if (textareaRef.value) {
    textareaRef.value.style.height = 'auto';
    textareaRef.value.style.height = `${textareaRef.value.scrollHeight}px`;
  }
};

watch(newMessage, autoResizeTextarea);

const sendMessage = () => {
  const trimmedMessage = newMessage.value.trim();
  if (!trimmedMessage || isLoading.value) {
    return;
  }

  addMessage('user', trimmedMessage);
  
  newMessage.value = '';
  isLoading.value = true;
  nextTick(() => autoResizeTextarea()); // Reset textarea height

  const url = `${API_BASE_URL}/ai/chat?memoryId=${memoryId.value}&message=${encodeURIComponent(trimmedMessage)}`;
  const eventSource = new EventSource(url);
  let aiMessageId = null;

  eventSource.onmessage = (event) => {
    if (event.data) {
      if (aiMessageId === null) {
        const newAiMessage = { id: getUniqueMessageId(), sender: 'ai', text: event.data };
        aiMessageId = newAiMessage.id;
        messages.value.push(newAiMessage);
      } else {
        const aiMessage = messages.value.find(m => m.id === aiMessageId);
        if (aiMessage) {
          aiMessage.text += event.data;
        }
      }
      scrollToBottom();
    }
  };

  eventSource.onerror = () => {
    eventSource.close();
    isLoading.value = false;
    if (aiMessageId === null) {
      addMessage('ai', '抱歉，与服务器的连接发生错误，请稍后重试。');
    }
  };
};

const handleKeydown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
};
</script>

<template>
  <div id="chat-app">
    <header class="chat-header">
      <h1>AI编程助手</h1>
    </header>
    <div class="chat-container" ref="chatContainer">
      <div
        v-for="message in messages"
        :key="message.id"
        class="message-wrapper"
        :class="['message-' + message.sender]"
      >
        <div class="message-content">
          <p v-text="message.text"></p>
        </div>
      </div>
    </div>
    <footer class="chat-footer">
      <div class="input-container">
        <textarea
          ref="textareaRef"
          v-model="newMessage"
          @keydown="handleKeydown"
          class="message-input"
          placeholder="向 AI 提问..."
          :disabled="isLoading"
          rows="1"
        ></textarea>
        <button @click="sendMessage" class="send-button" :disabled="isLoading || !newMessage.trim()">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
        </button>
      </div>
    </footer>
  </div>
</template>
